package uk.co.droidinactu.common.db;

import java.io.File;

import uk.co.droidinactu.common.file.FileUtilities;
import uk.co.droidinactu.common.model.Preference;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Environment;
import android.util.Log;

/**
 * This class helps open, create, and upgrade the database file.
 * 
 * @author andy
 */
public abstract class AbstractDatabaseHelper extends SQLiteOpenHelper {

    private final AbstractDbConstants dbConstants;

    public AbstractDatabaseHelper(final Context context, final AbstractDbConstants dbCnstants) {
        super(context, dbCnstants.getDbName(), null, dbCnstants.getDbVersion());
        dbConstants = dbCnstants;
    }

    @Override
    public void onCreate(final SQLiteDatabase db) {
        Log.w("DatabaseHelper", "Creating database version " + dbConstants.getDbVersion());
        db.execSQL(new Preference().getSqlCreate());
    }

    @Override
    public void onOpen(final SQLiteDatabase db) {
        super.onOpen(db);
        if (dbConstants.runInDebugMode()) {
            try {
                final File dbFile = new File(db.getPath());
                final File extDir = Environment.getExternalStorageDirectory();
                final File dbFileBackup = new File(extDir + File.separator + "dbBak" + dbConstants.getDbName() + ".db");
                dbFileBackup.delete();
                FileUtilities.copyFile(dbFile, dbFileBackup);
                Log.d("Cmn:AbDbHelper", "database backed up to file [" + dbFileBackup.getAbsolutePath() + "]");
            } catch (final Exception e) {
                // e.printStackTrace();
                Log.d("Cmn:AbDbHelper", "database backup failed");
            }
        }
    }

    @Override
    public void onUpgrade(final SQLiteDatabase db, final int oldVersion, final int newVersion) {
        Log.w("DatabaseHelper", "Upgrading database from version " + oldVersion + " to " + newVersion
                + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS " + new Preference().getTableName());
    }
}
